package com.codegeek.project.slope.controller;

import com.alibaba.fastjson.JSON;
import com.codegeek.common.utils.SecurityUtils;
import com.codegeek.common.utils.poi.ExcelUtil;
import com.codegeek.framework.aspectj.lang.annotation.Log;
import com.codegeek.framework.aspectj.lang.enums.BusinessType;
import com.codegeek.framework.web.controller.BaseController;
import com.codegeek.framework.web.domain.AjaxResult;
import com.codegeek.framework.web.page.TableDataInfo;
import com.codegeek.project.slope.domain.*;
import com.codegeek.project.slope.service.ISlopeCameraService;
import com.codegeek.project.slope.service.ISlopeDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 摄像头Controller
 *
 * @author codegeek
 * @date 2020-02-17
 */
@RestController
@RequestMapping("/slope/camera")
@Api(value="摄像头Controller",tags={"摄像头操作接口"})
public class SlopeCameraController extends BaseController
{
    @Autowired
    private ISlopeCameraService slopeCameraService;

    @Autowired
    private ISlopeDeviceService slopeDeviceService;

    /**
     * 查询摄像头列表
     */
    @ApiOperation("查询摄像头列表")
    @PostMapping("/list")
    @PreAuthorize("@ss.hasPermi('slope:camera:list')")
    public TableDataInfo list(@RequestBody SlopeCamera slopeCamera)
    {
        startPage();
        List<SlopeCamera> list = slopeCameraService.selectSlopeCameraList(slopeCamera);
        return getDataTable(list);
    }

    /**
     * 查询首页摄像头列表
     */
    @ApiOperation("查询首页摄像头列表")
    @GetMapping("/indexCamera")
    @PreAuthorize("@ss.hasPermi('slope:camera:indexCamera')")
    public TableDataInfo indexCamera(SlopeCamera slopeCamera)
    {
        startPage();
        List<SlopeCamera> list = slopeCameraService.selectSlopeCameraList(slopeCamera);
        return getDataTable(list);
    }

    /**
     * 检查新增摄像头名称是否重复
     * @param name
     * @return
     */
    @ApiOperation("检查新增摄像头名称是否重复")
    @GetMapping("/checkCameraName")
    public AjaxResult checkCameraName(String name){
        return AjaxResult.success(slopeCameraService.checkCameraName(name));

    }

    /**
     * 导出摄像头列表
     */
    @ApiOperation("导出摄像头列表")
    @Log(title = "监测管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermi('slope:camera:export')")
    public AjaxResult export(SlopeCamera slopeCamera)
    {
        List<SlopeCamera> list = slopeCameraService.selectSlopeCameraList(slopeCamera);
        ExcelUtil<SlopeCamera> util = new ExcelUtil<SlopeCamera>(SlopeCamera.class);
        return util.exportExcel(list, "camera");
    }

    /**
     * 获取摄像头详细信息
     */
    @ApiOperation("获取摄像头详细信息")
    @GetMapping(value = "/getInfo/{cameraId}")
    @PreAuthorize("@ss.hasPermi('slope:camera:getInfo')")
    public AjaxResult getInfo(@PathVariable("cameraId") Long cameraId)
    {
        return AjaxResult.success(slopeCameraService.selectSlopeCameraById(cameraId));
    }

    /**
     * 新增摄像头
     */
    @ApiOperation("新增摄像头")
    @Log(title = "监测管理", businessType = BusinessType.INSERT)
    @PostMapping
    @PreAuthorize("@ss.hasPermi('slope:camera:add')")
    public AjaxResult add(@RequestBody SlopeAddCamera addCamera)
    {
        SlopeDevice slopeDevice = new SlopeDevice();
        slopeDevice.setSupplierId(addCamera.getSupplierId());
        slopeDevice.setDeviceType(3);
        slopeDevice.setDeviceName(addCamera.getDeviceName());
        slopeDevice.setDescription(addCamera.getDescription());
        slopeDevice.setNumber(addCamera.getNumber());
        slopeDevice.setState(0);
        slopeDevice.setIsValid("0");
        slopeDevice.setPointId(addCamera.getPointId());
        slopeDevice.setJoinTime(new Date());
        slopeDevice.setOnlineTime(new Date());
        slopeDevice.setCreateTime(new Date());
        slopeDevice.setCreateBy(SecurityUtils.getUsername());
        slopeDeviceService.insertSlopeDevice(slopeDevice);
        SlopeCamera camera = new SlopeCamera();
        camera.setDeviceId(Long.valueOf(slopeDevice.getDeviceId()));
        camera.setAccessToken(addCamera.getAccessToken());
        camera.setNvrId(addCamera.getNvrId());
        camera.setChannel(addCamera.getChannel());
        camera.setValidateCode(addCamera.getValidateCode());
        camera.setCreateTime(new Date());
        camera.setCreateBy(SecurityUtils.getUsername());
        camera.setCameraType(addCamera.getCameraType());
        return toAjax(slopeCameraService.insertSlopeCamera(camera));
    }

    /**
     * 修改摄像头
     */
    @ApiOperation("修改摄像头")
    @Log(title = "监测管理", businessType = BusinessType.UPDATE)
    @PostMapping("/updateCamera")
    @PreAuthorize("@ss.hasPermi('slope:camera:updateCamera')")
    public AjaxResult edit(@RequestBody SlopeAddCamera addCamera)
    {
        SlopeCamera camera = slopeCameraService.selectSlopeCameraById(addCamera.getCameraId());
        SlopeDevice device = slopeDeviceService.selectSlopeDeviceById(camera.getDeviceId());
        device.setDeviceName(addCamera.getDeviceName());
        device.setNumber(addCamera.getNumber());
        device.setSupplierId(addCamera.getSupplierId());
        device.setPointId(addCamera.getPointId());
        device.setDescription(addCamera.getDescription());
        slopeDeviceService.updateSlopeDevice(device);
        camera.setValidateCode(addCamera.getValidateCode());
        camera.setNvrId(addCamera.getNvrId());
        camera.setChannel(addCamera.getChannel());
        camera.setCameraType(addCamera.getCameraType());
        return toAjax(slopeCameraService.updateSlopeCamera(camera));
    }

    /**
     * 删除摄像头
     */
    @ApiOperation("删除摄像头")
    @Log(title = "监测管理", businessType = BusinessType.DELETE)
	@PostMapping("/remove/{cameraIds}")
    @PreAuthorize("@ss.hasPermi('slope:camera:remove')")
    public AjaxResult remove(@PathVariable Long[] cameraIds)
    {
        return toAjax(slopeCameraService.deleteSlopeCameraByIds(cameraIds));
    }


    //开始云台控制
    private static String ptzStart = "https://open.ys7.com/api/lapp/device/ptz/start";

    //停止云台控制
    private static String ptzStop = "https://open.ys7.com/api/lapp/device/ptz/stop";
    /**
     * 控制摄像头
     */
    @ApiOperation("控制摄像头")
    @Log(title = "控制摄像头", businessType = BusinessType.UPDATE)
    @PostMapping("/controlCamera")
    @PreAuthorize("@ss.hasPermi('slope:camera:controlCamera')")
    public AjaxResult controlCamera(@RequestBody CameraParams cameraParams)
    {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("accessToken",cameraParams.getAccessToken());//access_token
        map.add("deviceSerial",cameraParams.getDeviceSerial());//设备序列号
        map.add("channelNo",cameraParams.getChannelNo()+"");//通道号
        String url ="";
        if(cameraParams.getDirection()==-1){
            url = ptzStop;
        }else{
            url = ptzStart;
            map.add("direction",cameraParams.getDirection()+"");//操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
            map.add("speed",cameraParams.getSpeed()+"");//云台速度：0-慢，1-适中，2-快，海康设备参数不可为0
        }
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
        Map<String,Object> dataMap = JSON.parseObject(response.getBody(), Map.class);
        if(dataMap.get("code").toString().equals("200")) {
            return AjaxResult.success(dataMap.get("msg").toString());
        }else{
            return AjaxResult.error("海康服务器异常！");
        }
    }

    //设备回放记录url
    private static String videoByTime = "https://open.ys7.com/api/lapp/video/by/time";
    /**
     * 获取摄像头详细信息
     */
    @ApiOperation("获取摄像头指定时间内历史回放记录")
    @Log(title = "获取摄像头指定时间内历史回放记录")
    @GetMapping(value = "getVideoByTime")
    @PreAuthorize("@ss.hasPermi('slope:camera:getVideoByTime')")
    public AjaxResult getVideoByTime(CameraParams cameraParams)
    {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
            //access_token
            map.add("accessToken",cameraParams.getAccessToken());
            //设备序列号
            map.add("deviceSerial",cameraParams.getDeviceSerial());
            //通道号
            map.add("channelNo",cameraParams.getChannelNo()+"");
            if(cameraParams.getStartTime()!=null&&!cameraParams.getStartTime().equals("")) {
                //起始时间，时间格式为：1378345128000。非必选，默认为当天0点
                map.add("startTime", cameraParams.getStartTime());
            }
            if(cameraParams.getEndTime()!=null&&!cameraParams.getEndTime().equals("")) {
                //起始时间，时间格式为：1378345128000。非必选，默认为当天0点
                map.add("endTime", cameraParams.getEndTime() + "");
            }
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = restTemplate.postForEntity( videoByTime, request , String.class );
            Map<String,Object> dataMap = JSON.parseObject(response.getBody(), Map.class);
            if(dataMap.get("code").toString().equals("200")) {
                return AjaxResult.success(dataMap.get("data"));
            }else{
                return AjaxResult.error("海康服务器异常！");
            }
        } catch (Exception e) {
            return AjaxResult.error("海康服务器异常！");
        }
    }



}
